(function($){
	var KEY = "jforest.loading";

	var Loading = function(element,options){
		this.el = element;
		this.options = $.extend({
			offset:50,
			height:'auto',
			auto:true,
			next:true,
			pageNo:1,
			lock:false,
			delay:0,
			callback:function(){}
		},options);
		
		var self = this,opts = this.options;
		$(element).css('overflow','scroll');
		if(opts.height == 'auto'){
			$(element).height($(window).height()).parent().height($(window).height());
		}else{
			$(element).height(opts.height);
		}
		$(element).scroll(function(){
			if(opts.next){
				var scrollTop = $(document).scrollTop();
				var offset = ($(document).height() - $(window).height() - opts.offset);
				if(scrollTop - offset >= 0 && opts.lock == false){
					opts.lock = true;
					opts.callback.apply(self,[opts.pageNo]);
					opts.pageNo = opts.pageNo + 1;
				}
			}
		});
		if(opts.auto){
			opts.lock = true;
			opts.callback.apply(self,[opts.pageNo]);
			opts.pageNo = opts.pageNo + 1;
		}
		if(opts.delay > 0){setTimeout(function(){self.reset()},opts.delay);}
	}
	
	Loading.prototype = {
		endRefresh:function(next){
			this.options.next=next;
			this.options.lock=false;
		},
		reset:function(){this.options.next=true;this.options.lock=false;this.options.pageNo=1;$(this.el).scroll()}
	}
	
	$.fn.jfLoading = function(){
		var args = Array.prototype.slice.call(arguments, 0);
		var value = undefined;
		this.each(function () {
			var $this = $(this);
			if (args.length === 0 || typeof(args[0]) === "object") {
				opts = args.length === 0 ? {} : $.extend({}, args[0]);
				value = new Loading(this,opts);$this.data(KEY,value); //创建控件
			}else if (typeof(args[0]) === "string"){
				var entity = $this.data(KEY);
                if(entity === undefined){return;}
                value = entity[args[0]].apply(entity, args.slice(1));
			}else{
				 throw 'Invalid arguments to '+KEY+' plugin: ' + args;
			}
	    });
	    return (value === undefined) ? this : value;
	};
	
	$.fn.jfLoading.Constructor = Loading;
	
})(window.jQuery)